package com.anysoft.user;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.UserBean;
import com.anysoft.utils.AESUtils;
import com.anysoft.utils.BitmapUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.orhanobut.logger.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Hashtable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.anysoft.utils.BitmapUtils.getDiskBitmap;

/**
 * Created by wwq on 2017/3/15.
 */

public class QRCodeActivity extends BaseActivity {

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.civ_qr_code_user_icon)
    CircleImageView civQrCodeUserIcon;
    @BindView(R.id.tv_icon_login_username)
    TextView tvIconLoginUsername;
    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;

    private Bitmap compoundBitmap;
    private Bitmap coreBitmap;

    private String userInfo;
    private String userName;
    private String userTell;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_qr_code);
        ButterKnife.bind(this);

        title.setText("我的二维码");

        userName = mentorApplication.accountLoginBean.getData().getRealName();
        userTell = mentorApplication.accountLoginBean.getData().getMobileNo();

        try {
            userInfo = str2json();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {

        UserBean userBean = findUser(mentorApplication.userBean.getUserId());
        if (userBean != null) {
            String pathUrl = userBean.getUserImgPath();
            if (!TextUtils.isEmpty(pathUrl)) {
                Logger.t("pathUrl").d(pathUrl);
                coreBitmap = getDiskBitmap(pathUrl);
                if (coreBitmap != null) {
                    civQrCodeUserIcon.setImageBitmap(coreBitmap);
                }
            } else {
                if ("0".equals(userBean.getSex())) {//女
                    civQrCodeUserIcon.setImageResource(R.mipmap.icon_user_w);
                } else if ("1".equals(userBean.getSex())) {//男
                    civQrCodeUserIcon.setImageResource(R.mipmap.icon_user_m);
                } else {
                    civQrCodeUserIcon.setImageResource(R.mipmap.icon_user);
                }
//                civQrCodeUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
            }
        } else {
            civQrCodeUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
        }
        tvIconLoginUsername.setText(userName);

        Bitmap qrcodeBitmap = null;
        if (!TextUtils.isEmpty(userInfo)) {
            try {
                int qrcodeSize = getResources().getDimensionPixelSize(R.dimen.qrcode_size);
                qrcodeBitmap = CreateTwoDCode(userInfo, qrcodeSize);
            } catch (WriterException e) {
                showToast("生成二维码失败");
            }
        }
        if (qrcodeBitmap != null) {
            Bitmap iconBitmap = coreBitmap != null ? coreBitmap : BitmapFactory.decodeResource(getResources(), R.mipmap.icon_cash_line);
            int icon_cash_line_size = getResources().getDimensionPixelSize(R.dimen.icon_cash_line_size);

            // 创建一个新的空的Bitmap
            Bitmap newIcon = Bitmap.createBitmap(icon_cash_line_size, icon_cash_line_size, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(newIcon);

            Rect src = new Rect(0, 0, iconBitmap.getWidth(), iconBitmap.getHeight());
            RectF dst = new RectF(0, 0, icon_cash_line_size, icon_cash_line_size);
            canvas.drawBitmap(iconBitmap, src, dst, null);
            canvas.save(Canvas.ALL_SAVE_FLAG);                    // 保存
            canvas.restore();

            compoundBitmap = BitmapUtils.compoundBitmap(qrcodeBitmap, newIcon);
            ivQrCode.setImageBitmap(compoundBitmap);
        }
    }

    @OnClick(R.id.leftButton)
    public void onClick() {
        finish();
    }

    private String str2json() throws UnsupportedEncodingException {
        StringBuffer buffer = new StringBuffer();
        String tell = AESUtils.encrypt("ICBCCS_Magus", userTell);    // 把电话加密码
        String bindCustomerUrl = HostConstant.BIND_CUSTOMER + "broker=" + URLEncoder.encode(userName, "UTF-8") + "&tel=" + userTell + "&type=2&accoDate=10000&tranDate=3";
        Logger.i(TAG, "bindCustomerUrl = " + bindCustomerUrl);
        buffer.append("BEGIN:").append("VCARD").append("\n")
                .append("VERSION:").append("3.0").append("\n")
//					.append("TEL:").append(tell).append("\n")
                .append("ICCellPhone:").append(tell).append("\n")
                .append("N:").append(userName).append("\n")
//					.append("URL:").append("https://ydxjb.icbccs.com.cn/GYRX-2.0/ICBCAppDown.html?userName=" + userName + "&phone=" + userTell).append("\n")
                .append("URL:").append(bindCustomerUrl).append("\n")
                .append("END:VCARD").append("\n");
        return buffer.toString();
    }

    /**
     * 将指定的内容生成成二维码
     *
     * @param content 将要生成二维码的内容
     * @return 返回生成好的二维码事件
     * @throws WriterException WriterException异常
     */
    public Bitmap CreateTwoDCode(String content, int qrcodeSize) throws WriterException {

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//解决中文乱码
        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrcodeSize, qrcodeSize, hints);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 二维矩阵转为一维像素数组,也就是一直横着排了
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                } else {
                    pixels[y * width + x] = 0xffffffff;
                }
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // 通过像素数组生成bitmap,具体参考api
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
}
